﻿using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UserModels;
using UserModels.DTO;
using UserRepositorys.Intface;

namespace UserRepositorys.Impl
{
    public class TiesRepository : Repository<TiesInfoModel>, ITiesRepository
    {
        private readonly IRoleRepository roleRepository;
        public TiesRepository(ISqlSugarClient db, IRoleRepository roleRepository) : base(db)
        {
            this.roleRepository = roleRepository;
        }
        /// <summary>
        /// 添加关系
        /// </summary>
        /// <param name="roleMenuInfo"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<int> AddRoleMune(RoleMenuInfoDTO roleMenuInfo)
        {
            var a = await roleRepository.GetRoleAllList();
            var b = a.Where(x => x.RoleName == roleMenuInfo.RoleName);
            var c = b.FirstOrDefault();
            var menuIds = roleMenuInfo.MenuId.Split(',');
            foreach (var id in menuIds)
            {
                var roleMenus = await base.GetAllasync();
                roleMenus = roleMenus.Where(x => x.RoleId == roleMenuInfo.RoleId && menuIds.Contains(x.MenuId.ToString())).ToList();

                foreach (var item in roleMenus)
                {
                    await base.Deleteasync(item.TiesId);
                }
            }

            //添加
            List<int> ints = new List<int>();
            foreach (var item in menuIds)
            {
                TiesInfoModel infoModel = new TiesInfoModel();
                infoModel.MenuId = Convert.ToInt32(item);
                infoModel.RoleId = c.RoleId;
                var count = await base.Addasync(infoModel);
                ints.Add(count);
            }

            return ints.Count;

        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="roleId"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<int> DeleteRoleMune(int roleId)
        {
            var list = await roleRepository.DeleteRole(roleId);
            var tiesList = await base.GetAllAsync(x => x.RoleId == roleId);
            foreach (var item in tiesList)
            {
                await base.Deleteasync(item.TiesId);
            }
            return list;
        }
    }
}
